package com.it2297.model;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import com.it2297.main.App;

public class OrderItem {

	private int Quantity;
	private int ProdID;
	private int OrderID;

	public int getQuantity() {
		return Quantity;
	}

	public void setQuantity(int quantity) {
		Quantity = quantity;
	}

	public int getProdID() {
		return ProdID;
	}

	public void setProdID(int prodID) {
		ProdID = prodID;
	}

	public int getOrderID() {
		return OrderID;
	}

	public void setOrderID(int orderID) {
		OrderID = orderID;
	}

	public void CreateOrderItem(OrderItem item) {
		try {
			App.mySqlConnection.open();
			String sql = "INSERT INTO americano.order_item(quantity, product_id, order_id)";
			sql += "VALUES(?,?,?)";
			PreparedStatement ps = App.mySqlConnection.getConnection().prepareStatement(sql);
			ps.setInt(1, item.getQuantity());
			ps.setInt(2, item.getProdID());
			ps.setInt(3, item.getOrderID());

			ps.executeUpdate();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			App.mySqlConnection.close();
		}
	}
	
	public void deleteItem(int id){
		try {
			App.mySqlConnection.open();
			String sql = "DELETE  FROM americano.order_item WHERE order_id =?";
			PreparedStatement ps = App.mySqlConnection.getConnection().prepareStatement(sql);
			ps.setInt(1, id);
			ps.executeUpdate();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			App.mySqlConnection.close();
		}
	}
	
	
	public ArrayList<OrderItem> getSelectedItem(int orderid){
		ArrayList<OrderItem> item = new ArrayList<OrderItem>();
		
		try {
			App.mySqlConnection.open();
			String sql ="SELECT * FROM americano.order_item where order_id=? order by order_id";
			PreparedStatement ps = App.mySqlConnection.getConnection().prepareStatement(sql);
			ps.setInt(1, orderid);
			
			ResultSet rs = ps.executeQuery();
			
			while(rs.next()){
				OrderItem temp = new OrderItem();
				temp.setAttributes(rs);
				item.add(temp);
			}
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			App.mySqlConnection.close();
		}
		
		return item;
	}
	
	private void setAttributes(ResultSet rs) {

		try {
			this.setQuantity(rs.getInt("quantity"));
			this.setProdID(rs.getInt("product_id"));
			this.setOrderID(rs.getInt("order_id"));
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
